package com.xiaochong.bitong.api.service;

import com.alibaba.fastjson.JSON;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.bitong.api.component.RedisCacheComponent;
import com.xiaochong.bitong.api.constant.ReturnCode;
import com.xiaochong.bitong.api.utils.Base64ToImages;
import com.xiaochong.service.common.config.oss.OSSTool;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.common.data.po.CurrencyInfo;
import com.xiaochong.tir.common.data.redisPo.CoinPriceVo;
import com.xiaochong.tir.common.data.vo.ApiMarketAnalysisTotalResult;
import com.xiaochong.tir.common.data.vo.ApiResultVo;
import com.xiaochong.tir.common.data.vo.app.MarketIndexVo;
import com.xiaochong.tir.common.data.vo.app.VxCurrencyMarketVo;
import com.xiaochong.tir.common.data.vo.app.VxCurrencyVo;
import com.xiaochong.tir.common.data.vo.app.VxGlobalIndexVo;
import com.xiaochong.tir.common.util.OssImageUtil;
import com.xiaochong.tir.common.util.RedisKeyApp;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: vx
 * @Author: org
 * @CreateDate: 2018/9/13 14:51
 */
@Service
public class VxRobotService {

    @Autowired
    private RedisServer redisServer;
    @Autowired
    private RedisCacheComponent redisCacheComponent;

    @Autowired
    OSSTool ossTool;

    @Autowired
    OssImageUtil ossImageUtil;

    public ApiResultVo<VxCurrencyVo> getCurrencyCollects() {
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        List<CurrencyInfo> currencyInfoList = redisCacheComponent.getCurrencyList();
        if(currencyInfoList!= null && currencyInfoList.size() > 0){
            List<VxCurrencyVo> voList = new ArrayList<>();
            VxCurrencyVo vo ;
            for(CurrencyInfo currencyInfo :currencyInfoList){
                vo = new VxCurrencyVo();
                vo.setCmcId(currencyInfo.getCmcId()!=null?currencyInfo.getCmcId():"");
                vo.setCoinNameCn(currencyInfo.getCoinNameCn()!=null?currencyInfo.getCoinNameCn():"");
                vo.setCoinNameEn(currencyInfo.getCoinNameEn()!=null?currencyInfo.getCoinNameEn():"");
                vo.setSymbol(currencyInfo.getSymbol()!=null?currencyInfo.getSymbol():"");
                vo.setId(currencyInfo.getId());
                voList.add(vo);
            }
            resultVo.setData( voList );
            resultVo.setCode(ReturnCode.SUCCESS);
            resultVo.setMessage("成功");
        }else{
            resultVo.setCode(ReturnCode.DATA_NOT_EXIST);
            resultVo.setMessage("未查询到数据");
        }
        return resultVo;
    }

    public ApiResultVo<VxCurrencyMarketVo> getCurrencyMarket(String cmcId) {
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        if(StringUtils.isBlank(cmcId)){
            resultVo.setCode(ReturnCode.PARAMS_ERROR);
            resultVo.setMessage("参数不能为空");
            return resultVo;
        }
        try {
            LogTrace.infoKvs("机器人货币行情","cmcId",cmcId);
            VxCurrencyMarketVo vo = new VxCurrencyMarketVo();
            String priceRedisKey = RedisKeyApp.COIN_PRICE+cmcId;
            String priceRedisData = redisServer.get(priceRedisKey);
            CoinPriceVo coinPriceVo;
            if(StringUtils.isNotBlank(priceRedisData)){
                coinPriceVo = JSON.parseObject(priceRedisData,CoinPriceVo.class);
            }else{
                coinPriceVo = new CoinPriceVo();
            }
            if(coinPriceVo == null || coinPriceVo.getPriceCny() == null || coinPriceVo.getPriceUsd() == null){
                resultVo.setCode(ReturnCode.DATA_NOT_EXIST);
                resultVo.setMessage("未查询到价格");
                return resultVo;
            }
            vo.setChang24h(coinPriceVo.getChang24h()!=null?coinPriceVo.getChang24h():"-");
            vo.setAmount24H(coinPriceVo.getAmount24H()!=null?coinPriceVo.getAmount24H():"-");
            vo.setCoinNameCn(coinPriceVo.getCoinNameCn());
            vo.setDatetime(coinPriceVo.getDatetime());
            vo.setPriceCny(coinPriceVo.getPriceCny());
            vo.setPriceUsd(coinPriceVo.getPriceUsd());
            vo.setRank(coinPriceVo.getRank());
            vo.setSymbol(coinPriceVo.getSymbol());
            String grail = redisServer.get(RedisKeysUtils.CMC_DATA_7_STATUS+cmcId);
            //vo.setLast7status(redisServer.get(RedisKeysUtils.CMC_DATA_7_STATUS+cmc_id));
            if(StringUtils.isNotBlank(grail)){
               // ApiMarketAnalysisTotalResult m = JSON.parseObject(grail,ApiMarketAnalysisTotalResult.class);
                vo.setExplain(grail);
            }else{
                vo.setExplain("-");
            }
            resultVo.setData(vo);
            resultVo.setCode(ReturnCode.SUCCESS);
            resultVo.setMessage("成功");
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("机器人货币行情-error",e);
            resultVo.setCode(ReturnCode.ERROR);
            resultVo.setMessage("异常");
        }
        return resultVo;
    }


    public ApiResultVo<VxGlobalIndexVo> getCurrencyMarketIndex() {
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            VxGlobalIndexVo result = new VxGlobalIndexVo();
            String global = redisServer.get(RedisKeysUtils.GLOBAL_INDEX_VX_ROBOT);
            if(StringUtils.isNotBlank(global)){
                result = JSON.parseObject(global,VxGlobalIndexVo.class);
                MarketIndexVo marketIndexVo = redisServer.get(RedisKeyApp.MARKET_DATA , MarketIndexVo.class);
                if(marketIndexVo != null){
                    result.setTotalVolume24h(StringUtils.isNotBlank(marketIndexVo.getTotalVolume24h())?marketIndexVo.getTotalVolume24h():"0");
                    result.setTotalMarketCap(StringUtils.isNotBlank(marketIndexVo.getTotalMarketCap())?marketIndexVo.getTotalMarketCap():"0");
                }
                resultVo.setData(result);
                resultVo.setCode(ReturnCode.SUCCESS);
                resultVo.setMessage("成功");
            }else{
                resultVo.setCode(ReturnCode.DATA_NOT_EXIST);
                resultVo.setMessage("未查询到价格");
            }

        }catch (Exception e){
            e.printStackTrace();
            resultVo.setCode(ReturnCode.ERROR);
            resultVo.setMessage("异常");
            LogTrace.error("机器人大盘行情-error",e);
        }
        return resultVo;
    }

    public ApiResultVo uploadImage(String imageString,String cmcId) {
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            if(StringUtils.isBlank(imageString)){
                resultVo.setCode(ReturnCode.PARAMS_ERROR);
                resultVo.setMessage("参数不能为空");
                return resultVo;
            }
           //base64转图片流
            InputStream inputStream = Base64ToImages.Base64ToInputStream(imageString);
            //上传
            boolean uploadFlag = true;
            if(null != inputStream){
                String key = "robot/currency/"+cmcId+".png";
                String url = "";
                if(ossTool.upload(inputStream , key)){
                    url = ossImageUtil.fmtImg(key);
                }
                if(StringUtils.isNotBlank(url) && !url.startsWith("Error")){
                    resultVo.setData(url);
                    resultVo.setCode(ReturnCode.SUCCESS);
                    resultVo.setMessage("成功");
                }else{
                    uploadFlag = false;
                }
            }else{
                uploadFlag = false;
            }
            if(!uploadFlag){
                resultVo.setCode(ReturnCode.ERROR);
                resultVo.setMessage("上传失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            resultVo.setCode(ReturnCode.ERROR);
            resultVo.setMessage("异常");
            LogTrace.error("机器人文件上传-error",e);
        }
        return resultVo;
    }

    public ApiResultVo getImageUrl(String cmcId) {
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            if(StringUtils.isBlank(cmcId)){
                resultVo.setCode(ReturnCode.PARAMS_ERROR);
                resultVo.setMessage("参数不能为空");
                return resultVo;
            }
            String key = "robot/currency/"+cmcId+".png";
            String url = ossImageUtil.fmtImg(key);
            resultVo.setData(url);
        }catch (Exception e){
            e.printStackTrace();
            resultVo.setCode(ReturnCode.ERROR);
            resultVo.setMessage("异常");
            LogTrace.error("机器人获取图片路径-error",e);
        }
        return resultVo;
    }
}
